<template>
  <div class="register">
    <div class="register-title">{{ $t('login.register') }}</div>
    <div class="register-form">
      <el-form :model="registerForm" ref="registerRef" :rules="registerRules">
        <el-form-item prop="name">
          <el-input
            v-model.number="registerForm.name"
            :placeholder="$t('login.enter-username')"
          />
        </el-form-item>
        <el-form-item prop="password">
          <div class="flex-1">
            <el-input
              v-model="registerForm.password"
              type="password"
              v-no-copy-paste
              show-password
              :placeholder="$t('login.enter-password')"
            />
            <core-password-strength
              :password="registerForm.password"
            ></core-password-strength>
            <p class="password-tips">{{ $t('login.password-requirements') }}</p>
          </div>
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            v-no-copy-paste
            show-password
            :placeholder="$t('login.enter-confirm-password')"
          />
        </el-form-item>
        <el-form-item prop="isAgreed">
          <el-checkbox v-model="registerForm.isAgreed">{{
            $t('login.i-agree')
          }}</el-checkbox>
          <span class="privacy-link">{{
            $t('login.privacy-policy-terms')
          }}</span>
        </el-form-item>
      </el-form>
    </div>
    <div class="register-button display-flex">
      <el-button
        class="flex-1"
        type="primary"
        :loading="registerLoading"
        @click="handleRegister"
        >{{ $t('login.register') }}</el-button
      >
    </div>
    <div class="account-info display-flex flex-justify">
      {{ $t('login.already-have-account') }}
      <span class="login-button" @click="handleEnter">{{
        $t('login.go-to-login')
      }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { usePreferencesStore } from '@/stores'
import { delay } from '@/utils'
import { loginPasswordRegex } from '@/utils/modules/regexp'
import type { FormInstance, FormRules } from 'element-plus'
import { reactive, ref, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'

const router = useRouter()
const { t } = useI18n()
const preferencesStore = usePreferencesStore()

const registerForm = ref({
  name: '',
  password: '',
  confirmPassword: '',
  isAgreed: false
})
const checkPasswordsMatch = (
  _rule: RuleItem,
  value: string,
  cb: RuleItemCb
) => {
  if (!value) return cb(new Error(t('login.enter-confirm-password')))
  if (value !== registerForm.value.password) {
    return cb(new Error(t('login.password-mismatch')))
  }
  cb()
}
const checkAgreed = (_rule: RuleItem, value: boolean, cb: RuleItemCb) => {
  if (!value) return cb(new Error(t('login.agree-privacy-policy-terms')))
  cb()
}
const registerRules = reactive<FormRules<typeof registerForm.value>>({
  name: [
    { required: true, message: t('login.enter-username'), trigger: 'blur' }
  ],
  password: [
    { required: true, message: t('login.enter-password'), trigger: 'blur' },
    {
      pattern: loginPasswordRegex,
      message: t('login.password-format-error'),
      trigger: ['change', 'blur']
    }
  ],
  confirmPassword: [
    {
      required: true,
      message: t('login.enter-confirm-password'),
      trigger: 'blur'
    },
    { validator: checkPasswordsMatch, trigger: ['change', 'blur'] }
  ],
  isAgreed: [
    {
      required: true,
      message: t('login.agree-privacy-policy-terms'),
      trigger: 'change'
    },
    { validator: checkAgreed, trigger: 'change' }
  ]
})

const registerRef = useTemplateRef<FormInstance>('registerRef')
const registerLoading = ref(false)
const handleRegister = async () => {
  registerLoading.value = true
  try {
    await registerRef.value?.validate()
    await delay(500)
    ElMessage.success(t('login.registration-successful'))
    router.replace('/login/enter')
  } catch (error) {
    return error
  } finally {
    registerLoading.value = false
  }
}

const handleEnter = () => {
  router.replace('/login/enter')
}

watch(
  () => preferencesStore.general.lang.language,
  () => {
    if (registerRules.password && Array.isArray(registerRules.password)) {
      registerRules.password[0].message = t('login.enter-password')
      registerRules.password[1].message = t('login.password-format-error')
    }
    if (registerRules.name && Array.isArray(registerRules.name)) {
      registerRules.name[0].message = t('login.enter-username')
    }
    if (
      registerRules.confirmPassword &&
      Array.isArray(registerRules.confirmPassword)
    ) {
      registerRules.confirmPassword[0].message = t(
        'login.enter-confirm-password'
      )
    }
  }
)

defineOptions({
  name: 'CoreRegister'
})
</script>

<style scoped lang="scss">
.register {
  margin: 24px 54px;

  .register-title {
    margin-bottom: 22px;
    font-size: 36px;
    font-weight: 700;
  }

  .register-form {
    .password-tips {
      margin-top: 6px;
      font-size: 12px;
      line-height: 16px;
      color: var(--core-text-color-05);
    }

    .privacy-link {
      margin-left: 6px;
      color: rgb(var(--core-primary-color));
      cursor: pointer;
    }
  }

  .account-info {
    margin-top: 16px;
    font-size: 14px;

    .login-button {
      color: rgb(var(--core-primary-color));
      cursor: pointer;
    }
  }
}
</style>
